<template>
  <el-dialog title="签证证件倒查回访工作记录反馈" :center="true" :visible.sync="visible" :modal-append-to-body="true" :append-to-body="true" custom-class="feedback-detail" @close="closeEvent" @open="dialogOpen" :lock-scroll="true">
    <div class="feedback-detail__con">
      <xdh-layout :east="{width: '345px',height: '100%'}" :west="{width: 'calc(100% - 400px)'}">
        <div class="feedback-info" slot="west">
          <div v-if="mode === 'view'" class="view">
            <el-form :inline="true" class="form-inline" :label-width="'220px'">
              <el-form-item v-for="(item, idx) in formDataList1" :key="idx" :label="item.label" :style="{width: item.width || '50%'}">
                <span class="value">{{item.value}}</span>
              </el-form-item>
            </el-form>
            <el-form :inline="true" class="form-inline" :label-width="'220px'">
              <el-form-item v-for="(item, idx) in formDataList2" :key="idx" :label="item.label" :style="{width: item.width || '50%'}">
                <span class="value">{{item.value}}</span>
              </el-form-item>
            </el-form>
          </div>
          <div v-if="mode === 'submit'" class="submit">
            <el-form :inline="true" class="form-inline" :label-width="'230px'">
              <el-form-item v-for="(item, idx) in formDataList1" :key="idx" :label="item.label">
                <span class="value">{{item.value}}</span>
              </el-form-item>
            </el-form>
            <el-form :model="formData" :rules="rules" :label-width="'230px'" ref="feedbackForm">
              <el-form-item label="单位信息是否一致" prop="workunit">
                <el-radio-group v-model="formData.workunit">
                  <el-radio label="1">是</el-radio>
                  <el-radio label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="住宿信息是否一致" prop="liveaddr">
                <el-radio-group v-model="formData.liveaddr">
                  <el-radio label="1">是</el-radio>
                  <el-radio label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="从事的活动与停居留是否相符" prop="workunit">
                <el-radio-group v-model="formData.workunit">
                  <el-radio label="1">是</el-radio>
                  <el-radio label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="是否有其他异常情况" prop="exception">
                <el-radio-group v-model="formData.exception">
                  <el-radio label="1">是</el-radio>
                  <el-radio label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="需要变更的事项或情况说明" prop="descript">
                <el-input type="textarea" v-model="formData.descript" :rows="3"></el-input>
              </el-form-item>
              <el-form-item label="回访民警" prop="feedbackUser" :inline-message="true" class="line-break">
                <el-input v-model="formData.feedbackUser" size="mini" readonly></el-input>
              </el-form-item>
              <el-form-item label="联系电话" prop="policetele" class="line-break" :inline-message="true">
                <el-input v-model="formData.policetele" size="mini"></el-input>
              </el-form-item>
              <el-form-item label="回访时间" prop="feedbackTime" class="line-break" :inline-message="true">
                <el-date-picker size="mini" v-model="formData.feedbackTime" type="datetime" placeholder="选择日期时间">
                </el-date-picker>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <xdh-panel title="附件" icon="iconfont icon-annex" class="attachment" slot="east">
          <xdh-grid class="grid-demo" :data="attachList" v-if="mode === 'view'" direction="row" justify="flex-start" wrap="wrap" align-content="flex-start">
            <div class="box-wrapper" slot-scope="scope">
              <attachment :imgId="scope.item.uuid" :viewOnly="true" :file-name="scope.item.name" @view="handlePicPreview"></attachment>
            </div>
          </xdh-grid>
          <el-upload v-if="mode === 'submit'" multiple ref="upload" :action="uploadPath" :on-success="onUploadSuccess" :on-preview="handlePicPreview" :on-remove="handleRemove" :accept="'image/jpeg,image/png'" :auto-upload="false" :with-credentials="true">
            <el-button size="small" type="primary">选择文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
          </el-upload>
        </xdh-panel>
      </xdh-layout>
    </div>
    <div slot="footer">
      <el-button type="primary" v-if="mode === 'submit'" @click="save()">保存</el-button>
      <el-button type="primary" @click="reSend()" v-if="mode === 'view'">
        <i class="iconfont icon-share"></i>
        重新下发</el-button>
    </div>
    <image-dialog :src="imageInfo.url" :file-name="imageInfo.fileName" :visible="imageShow" @close="closeImage"></image-dialog>
  </el-dialog>
</template>
<script>
  import XdhLayout from '@/widgets/xdh-layout';
  import XdhPanel from '@/widgets/xdh-panel';
  import XdhGrid from '@/widgets/xdh-grid';
  import Attachment from '@/components/common/attachment';
  import ImageDialog from '@/components/common/image-view';
  import checkfeedbacksMixin from '@/base/mixin/checkfeedbacks';
  import checkTaskMixin from '@/base/mixin/checktasks';
  import { UPLOAD_ATTACHMENT } from '@/config';
  import cookie from '@/helper/cookie';
  import { get } from '@/utils/storage';
  import date from '@/utils/date';
  export default {
    mixins: [checkfeedbacksMixin, checkTaskMixin],
    components: {
      XdhLayout,
      XdhPanel,
      Attachment,
      XdhGrid,
      ImageDialog
    },
    props: {
      visible: {
        type: Boolean
      },
      mode: {
        type: String,
        default: 'view'
      },
      feedbackId: {
        type: String,
        default: ''
      },
      rowData: {
        type: Object,
        default() {
          return {};
        }
      }
    },
    data() {
      return {
        imageShow: false,
        imageInfo: {
          url: '',
          name: ''
        },
        formData: {
          workunit: '1',
          liveaddr: '1',
          centrsn: '1',
          exception: '0',
          descript: '',
          feedbackUser: '',
          policetele: '',
          feedbackTime: ''
        },
        formMap: {
          国家地区: 'ccountry',
          英文姓名: 'enname',
          性别: 'csex',
          出生日期: 'birthday',
          联系电话: 'telephone',
          现持证件号码: 'passno',
          所持证件有效期至: '',
          申请签证种类: 'csigntype',
          申请事由: 'centrresn',
          '签证/居留许可号码': 'signno',
          签发日期: 'signdate',
          有效期至: 'signvali'
        },
        formDataList1: [],
        formMap2: {
          单位信息是否一致: 'workunit',
          住宿信息是否一致: 'liveaddr',
          从事的活动与停居留是否相符: 'centrsn',
          是否有其他异常情况: 'exception',
          需要变更的事项或情况说明: 'description',
          回访电话: 'policetele',
          回访民警: 'feedbackUser',
          回访时间: 'feedbackTime'
        },
        formDataList2: [],
        attachList: [
          {
            url: '/sub/static/img/head.jpg',
            name: 'abc地方大师傅十.jpg'
          },
          {
            url: '/static/img/default.jpg',
            name: 'default.jpg'
          },
          {
            url: '/static/img/timg.jpg',
            name: 'timg.jpg'
          },
          {
            url: '/static/img/head.d8081c3.ppt',
            name: 'abc.ppt'
          },
          {
            url: '/static/img/head.d8081c3.doc',
            name: 'abc地方大师傅.doc'
          },
          {
            url: '/static/img/head.d8081c3.mp3',
            name: 'abc地方大师傅.mp3'
          },
          {
            url: '/static/img/head.d8081c3.ttf',
            name: 'abc地方大师傅十.ttf'
          }
        ],
        attachmentCount: 0,
        finishCount: 0,
        uploadList: [],
        rules: {
          feedbackUser: [{ required: true, message: '请填写回访民警' }],
          workunit: [{ required: true, message: '请确认单位信息是否一致' }],
          liveaddr: [{ required: true, message: '请确认住宿信息是否一致' }],
          centrsn: [
            { required: true, message: '请确认从事的活动与停居留是否相符' }
          ],
          exception: [{ required: true, message: '请确认是否有其他异常情况' }],
          policetele: [
            { required: true, message: '请填写联系电话', trigger: 'blur' }
          ],
          feedbackTime: [
            { required: true, message: '请选择回访时间', trigger: 'blur' }
          ]
        }
      };
    },
    computed: {
      uploadPath() {
        return UPLOAD_ATTACHMENT + `?SESSION=${cookie('SESSION')}`;
      }
    },
    methods: {
      dateFormat2(val) {
        if (!val) {
          return '-';
        }
        let y = val.slice(0, 4);
        let m = parseInt(val.slice(4, 6)) - 1;
        let d = val.slice(6, 8);
        return date(new Date(y, m, d), 'yyyy-MM-dd');
      },
      dialogOpen() {
        // 打开对话框后，要等表单渲染成功才能进行下一步操作
        this.$nextTick(r => {
          this.reset();
          let userInfo = get('task_userInfo');
          if (userInfo) {
            this.formData.feedbackUser = userInfo.xm;
            this.formData.policetele = userInfo.sjhm;
          }
          if (this.rowData && this.rowData.pkValue) {
            // 以formMap为模板，以rowData为数据，得到一个包含label和value的数组，渲染出form-item
            for (let name in this.formMap) {
              let item = {
                label: name,
                value: this.rowData[this.formMap[name]] || ''
              };
              if (name === '有效期至') {
                item.value = this.dateFormat2(item.value);
              }
              this.formDataList1.push(item);
            }
          }
          // 如果有feedbackId，则查询反馈信息
          if (this.mode === 'view' && this.feedbackId) {
            this.getCheckfeedbacks(this.feedbackId, {}).then(res => {
              if (res) {
                // 以formMap2为模板，以查询到的结果为数据，得到一个包含label和value的数组，渲染出form-item
                for (let name in this.formMap2) {
                  let item = {
                    label: name,
                    value: res[this.formMap2[name]] || ''
                  };
                  if (name === '回访时间') {
                    item.value = item.value
                      ? date(new Date(item.value), 'yyyy-MM-dd hh:mm:ss')
                      : '';
                  }
                  if (
                    [
                      '单位信息是否一致',
                      '住宿信息是否一致',
                      '从事的活动与停居留是否相符',
                      '是否有其他异常情况'
                    ].includes(name)
                  ) {
                    item.value = item.value === 1 ? '是' : '否';
                  }
                  if (name === '需要变更的事项或情况说明') {
                    item.width = '100%';
                  }
                  this.attachList = res.accessories;
                  this.formDataList2.push(item);
                }
              }
            });
          }
        });
      },
      reset() {
        this.formDataList1 = [];
        this.formDataList2 = [];
        this.uploadList = [];
        this.attachList = [];
        this.attachmentCount = 0;
        this.finishCount = 0;
        this.formData = {
          workunit: '1',
          liveaddr: '1',
          centrsn: '1',
          exception: '0',
          descript: '',
          feedbackUser: '',
          policetele: '',
          uploads: '',
          feedbackTime: new Date()
        };
        // 如果未提交反馈页，则重置表单
        if (this.mode === 'submit' && this.$refs.feedbackForm) {
          this.$refs.feedbackForm.resetFields();
        }
        if (this.$refs.upload) {
          this.$refs.upload.clearFiles();
        }
      },
      closeImage() {
        this.imageShow = false;
      },
      closeEvent() {
        this.$emit('close');
      },
      onUploadSuccess(res, file, fileList) {
        // 统计上传成功的文件数，如果全部上传完，执行下一步提交表单
        this.finishCount++;
        // 这里需要改成res返回的url
        this.uploadList.push(res.data[0]);
        if (this.finishCount === this.attachmentCount) {
          this.submitForm();
        }
      },
      handleRemove(file, fileList) {
        return true;
      },
      // 这是给el-upload组件和attachment组件共用的预览方法
      handlePicPreview(file) {
        this.imageInfo.fileName = file.name;
        this.imageInfo.url = file.url;
        this.imageShow = true;
      },
      // 验证表单是否填写完整
      valid() {
        return new Promise((resolve, reject) => {
          this.$refs.feedbackForm.validate(valid => {
            if (valid) {
              resolve(true);
            } else {
              resolve(false);
            }
          });
        });
      },
      // 保存提交
      save() {
        this.valid().then(v => {
          if (v) {
            this.attachmentCount = this.$refs.upload.uploadFiles.length;
            //     // 如果没有选择任何附件，直接提交保存
            if (this.attachmentCount === 0) {
              this.submitForm();
            } else {
              this.$refs.upload.submit();
            }
          }
        });
      },
      submitForm() {
        let postData = Object.assign({}, this.formData, {
          feedbackTime: date(this.formData.feedbackTime, 'yyyy-MM-dd'),
          uploads: this.uploadList,
          pkTask: this.rowData.pkValue
        });
        this.addCheckfeedbacks(postData)
          .then(res => {
            this.closeEvent();
            this.$message({
              type: 'success',
              message: '提交反馈成功'
            });
          })
          .catch(e => {
            this.$message({
              type: 'warning',
              message: `提交反馈失败！${e}`
            });
          });
      },
      sendSuccess() {
        this.$message({
          type: 'success',
          message: '下发成功'
        });
        this.closeEvent();
      },
      reSend() {
        let postData = Object.assign({}, { id: this.rowData.pkTask });
        this.reCheckTask(postData).then(res => {
          if (res) {
            this.sendSuccess();
          }
        });
      }
    }
  };
</script>
<style type="text/scss" lang="scss">
  .box-wrapper {
    padding: 10px 5px;
  }
  $pic-size: 100px;
  .el-upload-list--picture-card .el-upload-list__item {
    width: $pic-size;
    height: $pic-size;
  }
  .el-upload--picture-card {
    width: $pic-size;
    height: $pic-size;
    line-height: $pic-size;
  }
</style>

<style type="text/scss" lang="scss">
  .attachment {
    min-height: 500px;
    .xdh-panel {
      height: 100%;
    }
  }
  .feedback-info {
    .el-form--inline .el-form-item {
      min-width: 50%;
      margin-right: 0;
    }
    .el-form-item {
      margin-right: 0;
      margin-bottom: 0;
    }
    .el-form-item {
      .el-form-item__label {
        font-size: 15px;
        font-weight: bold;
        line-height: 35px;
        &:after {
          content: ':';
        }
      }
      .el-form-item__content {
        font-size: 15px;
        line-height: 35px;
      }
    }
    .view {
      .el-form-item__content {
        max-width: calc(100% - 250px);
      }
    }
    .submit {
      .footer-input {
        .el-form-item {
          min-width: 30%;
        }
      }
      .el-form-item__error {
        margin-top: -6px;
      }
    }
  }
  .line-break.el-form-item {
    .el-form-item__label {
      width: 110px;
    }
    .el-input {
      max-width: 220px;
    }
  }
  @media screen and (max-width: 1553px) {
    .line-break.el-form-item {
      .el-form-item__label {
        width: 220px;
      }
    }
  }
</style>
<style  type="text/scss" lang="scss">
  .el-dialog.feedback-detail {
    margin: 1% !important;
    width: 98%;
  }
</style>